<?php

namespace app\adminapi\controller\v2\article;

use app\adminapi\controller\AuthController;
use app\model\article\ArticleType;
use think\exception\ValidateException;
use think\Request;

class Type extends AuthController
{
    public function list(Request $request)
    {
        $page = $request->param('page', 1);
        $limit = $request->param('size', 10);
        $type_name = $request->param('type_name', '');

        $data = ArticleType::order('sort')
            ->order('id', 'desc')
            ->where('status', 1)
            ->when($type_name, function ($query) use ($type_name) {
                return $query->where('type_name', 'like', '%' . $type_name . '%');
            })
            ->paginate($limit);

        return app('json')->success([
            'list' => $data->items(),
            'total' => $data->total(),
        ]);
    }

    public function info(Request $request)
    {
        $id = request()->param('id');
        $data = ArticleType::where('id', $id)
            ->where('status', 1)
            ->find();
        return app('json')->success([
            'data' => $data,
        ]);
    }

    public function save(Request $request)
    {
        $data = $request->only(['type_name', 'sort']);
        $id = input('id', '');
        try {
            validate([
                'type_name|分类名称' => 'require',
                'sort|排序' => 'require|number|min:0'
            ])->check($data);
        } catch (ValidateException $e) {
            return app('json')->fail($e->getError());
        }
        if ($id) {
            articletype::update($data, ['id' => $id]);
        } else {
            articletype::create($data);
        }
        return app('json')->success();
    }

    public function delete(Request $request)
    {
        $id = $request->param('id');
        $article = \app\model\article\Article::where('type_id', $id)
            ->where('status', 1)
            ->find();
        if ($article) {
            return app('json')->fail('该分类已使用，不可删除');
        }
        ArticleType::dataDelete($id);
        return app('json')->success();
    }
}